﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Net.Http;

namespace BW.Mes.WinForms.BasicData
{
    public partial class UpdateBomForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly string _apiBaseUrl = "https://localhost:7274";
        private readonly long _editId;
        public UpdateBomForm(BomForm.BomModel model)
        {
            InitializeComponent();
            comboBoxEditType.Properties.Items.Clear();
            comboBoxEditType.Properties.Items.AddRange(new string[] { "原材料", "半成品", "成品", "其他" });
            comboBoxEditType.Properties.NullText = "请选择类型";
            // 反填
            _editId = model.Id;
            textEditCode.Text = model.BomCode;
            textEditName.Text = model.BomName;
            textEditVersion.Text = model.Version;
            comboBoxEditType.Text = model.BomType;
            textEditNumber.Text = model.BomNumber;
            textEditMsg.Text = model.BomMsg;
        }
        private async void btnOK_Click(object sender, EventArgs e)
        {
            var model = new
            {
                Id = _editId,
                BomCode = textEditCode.Text,
                BomName = textEditName.Text,
                Version = textEditVersion.Text,
                BomType = comboBoxEditType.Text,
                BomNumber = textEditNumber.Text,
                BomMsg = textEditMsg.Text,
                UpdatedAt = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")
            };
            string jsonData = JsonConvert.SerializeObject(model);
            var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
            var client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            var response = await client.PutAsync($"{_apiBaseUrl}/api/Bom/UpdateBom", content);
            if (response.IsSuccessStatusCode)
            {
                XtraMessageBox.Show("修改成功！");
                this.DialogResult = DialogResult.OK;
            }
            else
            {
                XtraMessageBox.Show("修改失败！");
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}